// src/utils/ossUpload.js
import OSS from 'ali-oss';

let ossClient = null;
let expireTime = 0;

// 从服务端获取签名
async function getSignature() {
  const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/oss/sign`);
  return response.json();
}

// 初始化OSS客户端
async function initOSSClient() {
  // 如果已有客户端且未过期，直接返回
  if (ossClient && Date.now() < expireTime) {
    return ossClient;
  }
  
  // 获取新签名
  const { accessKeyId, accessKeySecret, stsToken, expire, region, bucket } = await getSignature();
  
  // 计算过期时间（提前5分钟刷新）
  expireTime = new Date(expire).getTime() - 300 * 1000;
  
  // 创建新客户端
  ossClient = new OSS({
    region,
    accessKeyId,
    accessKeySecret,
    stsToken,
    bucket,
    refreshSTSToken: async () => {
      const { accessKeyId, accessKeySecret, stsToken, expire } = await getSignature();
      expireTime = new Date(expire).getTime() - 300 * 1000;
      return {
        accessKeyId,
        accessKeySecret,
        stsToken
      };
    },
    refreshSTSTokenInterval: 300000 // 5分钟检查一次
  });
  
  return ossClient;
}

// 上传文件
export async function uploadFile(file, folder = 'uploads') {
  try {
    const client = await initOSSClient();
    
    // 生成唯一文件名
    const extension = file.name.split('.').pop();
    const fileName = `${folder}/${Date.now()}_${Math.random().toString(36).slice(2)}.${extension}`;
    
    // 分片上传（适合大文件）
    const result = await client.put(fileName, file, {
      progress: (p) => {
        console.log(`上传进度: ${Math.floor(p * 100)}%`);
      },
      headers: {
        'Content-Disposition': 'inline' // 设置文件在线预览
      }
    });
    console.log('上传成功:', result);
    return {
      url: result.url,
      name: fileName,
      size: file.size,
      type: file.type
    };
  } catch (err) {
    console.error('上传失败:', err);
    throw err;
  }
}

//获取文件访问的url
export async function getFileUrl(fileName) {
  try {
    const client = await initOSSClient();
    const url = client.signatureUrl(fileName,{
        expires: 3600, // 1小时有效
        method: 'GET'  // 获取权限
    });
    return url;
  } catch (err) {
    console.error('获取文件URL失败:', err);
    throw err;
  }
}